package org.openclinic.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.validation.Valid;

import org.openclinic.domain.Reminder;
import org.openclinic.exception.AbstractExceptionHandler;
import org.openclinic.exception.DomainException;
import org.openclinic.service.ReminderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ReminderController extends AbstractExceptionHandler {

	@Autowired
	private ReminderService reminderService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, "expireDate", new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
	}
	
	@ResponseBody
	@RequestMapping(value = "/reminder/delete.action", method = RequestMethod.POST)
	public boolean delete(@RequestParam int id) {
		reminderService.delete(id);
		return true;
	}
	
	@ResponseBody
	@RequestMapping(value = "/reminder/save.action", method = RequestMethod.POST)
	public Reminder save(@Valid @ModelAttribute Reminder reminder, BindingResult validationResult) {
		if(!validationResult.hasErrors()) {
			reminderService.save(reminder);
			return reminder;
		}
		throw new DomainException(validationResult.getAllErrors());
	}
	
}
